import {
    getProductDetail,
    getAddres
} from '../../api/article'
import {
    getId,
    submit,
    pay
} from '../../api/user'

// pages/product/product.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        addrs: [],
        product: {},
        show: false,
    },
    onClose() {
        this.setData({
            show: false
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    async onLoad(options) {
        console.log(options);
        if (options.id) {
            const res = await getProductDetail({
                goodsId: options.id
            })
            res.content.imgs = JSON.parse(res.content.imgs)
            this.setData({
                product: res.content
            })
        } else {
            this.setData({
                product: JSON.parse(options.item)
            })
        }

    },
    async initAddr() {
        const res = await getAddres({})
        this.setData({
            addrs: res.content
        })
    },

    handleSubmit() {
        
        if (!wx.getStorageSync('token')) {
            wx.showModal({
                title: '提示',
                content: '请登录后购买',
                complete: (res) => {
                    if (res.cancel) {

                    }
                    if (res.confirm) {
                        wx.switchTab({
                            url: '/pages/my/my',
                        })
                    }
                }
            })
            return
        }
        this.setData({
            show: true
        })
        this.initAddr()
    },
    async handleClickAddr(e) {
        this.setData({
            show:false
        })
        const ids = await getId({
            type: 2
        })
        const res = await submit({
            goodsId: this.data.product.id,
            num: 1,
            orderId: ids.content,
            addressId: e.currentTarget.dataset.id
        })
        const payres = await pay({
            orderId: ids.content
        })
        if (payres.content) {
            wx.requestPayment({
                nonceStr: payres.content.nonce_str,
                package: payres.content.package,
                paySign: payres.content.sign,
                signType: 'MD5',
                timeStamp: payres.content.timestamp,
                success(res) {
                    console.log(res)
                    wx.showToast({
                        title: '支付成功',
                        icon: 'success'
                    })
                },
                fail(err) {
                    console.log(err)
                    wx.showToast({
                        title: '支付失败',
                        icon: 'error'
                    })
                }
            })
        }
    }


})